package org.dfzt.modules.online.cgform.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;

import freemarker.template.TemplateException;
import org.dfzt.common.api.vo.Result;
import org.dfzt.common.system.query.QueryGenerator;
import org.dfzt.common.system.util.JwtUtil;
import org.dfzt.common.util.oConvertUtils;
import org.dfzt.modules.online.cgform.entity.OnlCgformEnhanceJava;
import org.dfzt.modules.online.cgform.entity.OnlCgformEnhanceJs;
import org.dfzt.modules.online.cgform.entity.OnlCgformEnhanceSql;
import org.dfzt.modules.online.cgform.entity.OnlCgformHead;
import org.dfzt.modules.online.cgform.enums.CgformEnum;
import org.dfzt.modules.online.cgform.mapper.OnlCgformEnhanceJavaMapper;
import org.dfzt.modules.online.cgform.service.IOnlCgformFieldService;
import org.dfzt.modules.online.cgform.service.IOnlCgformHeadService;
import org.dfzt.modules.online.config.exception.DBException;
import org.jeecgframework.codegenerate.database.DbReadTableUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController("onlCgformHeadController")
@RequestMapping({"/online/cgform/head"})
public class OnlCgformHeadController {
    private static final Logger a = LoggerFactory.getLogger(OnlCgformHeadController.class);


    @Autowired
    private IOnlCgformHeadService onlCgformHeadService;


    @Autowired
    private OnlCgformEnhanceJavaMapper onlCgformEnhanceJavaMapper;

    @Autowired
    private IOnlCgformFieldService onlCgformFieldService;

    private static final List<String> b = Lists.newArrayList(new String[]{"act_", "ext_act_", "design_", "onl_", "sys_", "qrtz_"});


    private static String c;


    @GetMapping({"/list"})
    public Result<IPage<OnlCgformHead>> a(OnlCgformHead paramOnlCgformHead, @RequestParam(name = "pageNo", defaultValue = "1") Integer paramInteger1, @RequestParam(name = "pageSize", defaultValue = "10") Integer paramInteger2, HttpServletRequest paramHttpServletRequest) {
        Result result = new Result();
        QueryWrapper queryWrapper = QueryGenerator.initQueryWrapper(paramOnlCgformHead, paramHttpServletRequest.getParameterMap());
        Page page = new Page(paramInteger1.intValue(), paramInteger2.intValue());
        IPage iPage = this.onlCgformHeadService.page(page, queryWrapper);
        if (paramOnlCgformHead.getCopyType() != null && paramOnlCgformHead.getCopyType().intValue() == 0) {
            this.onlCgformHeadService.initCopyState(iPage.getRecords());
        }
        result.setSuccess(true);
        result.setResult(iPage);
        return result;
    }


    @PostMapping({"/add"})
    public Result<OnlCgformHead> a(@RequestBody OnlCgformHead paramOnlCgformHead) {
        Result result = new Result();
        try {
            this.onlCgformHeadService.save(paramOnlCgformHead);
            result.success("添加成功！");
        } catch (Exception exception) {
            a.error(exception.getMessage(), exception);
            result.error500("操作失败");
        }
        return result;
    }


    @PutMapping({"/edit"})
    public Result<OnlCgformHead> b(@RequestBody OnlCgformHead paramOnlCgformHead) {
        Result result = new Result();
        OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(paramOnlCgformHead.getId());
        if (onlCgformHead == null) {
            result.error500("未找到对应实体");
        } else {
            boolean bool = this.onlCgformHeadService.updateById(paramOnlCgformHead);

            if (bool) {
                result.success("修改成功!");
            }
        }

        return result;
    }


    @DeleteMapping({"/delete"})
    public Result<?> a(@RequestParam(name = "id", required = true) String paramString) {
        try {
            this.onlCgformHeadService.deleteRecordAndTable(paramString);
        } catch (DBException dBException) {
            return Result.error("删除失败" + dBException.getMessage());
        } catch (SQLException sQLException) {
            return Result.error("删除失败" + sQLException.getMessage());
        }
        return Result.ok("删除成功!");
    }

    @DeleteMapping({"/removeRecord"})
    public Result<?> b(@RequestParam(name = "id", required = true) String paramString) {
        try {
            this.onlCgformHeadService.deleteRecord(paramString);
        } catch (DBException dBException) {
            return Result.error("移除失败" + dBException.getMessage());
        } catch (SQLException sQLException) {
            return Result.error("移除失败" + sQLException.getMessage());
        }
        return Result.ok("移除成功!");
    }


    @DeleteMapping({"/deleteBatch"})
    public Result<OnlCgformHead> a(@RequestParam(name = "ids", required = true) String paramString1, @RequestParam(name = "flag") String paramString2) {
        Result result = new Result();
        if (paramString1 == null || "".equals(paramString1.trim())) {
            result.error500("参数不识别！");
        } else {
            try {
                this.onlCgformHeadService.deleteBatch(paramString1, paramString2);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TemplateException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (DBException e) {
                e.printStackTrace();
            }
            result.success("删除成功!");
        }
        return result;
    }


    @GetMapping({"/queryById"})
    public Result<OnlCgformHead> c(@RequestParam(name = "id", required = true) String paramString) {
        Result result = new Result();
        OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(paramString);
        if (onlCgformHead == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(onlCgformHead);
            result.setSuccess(true);
        }
        return result;
    }


    @GetMapping({"/queryByTableNames"})
    public Result<?> d(@RequestParam(name = "tableNames", required = true) String paramString) {
        LambdaQueryWrapper<OnlCgformHead> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        String[] arrayOfString = paramString.split(",");
        lambdaQueryWrapper.in(OnlCgformHead::getTableName, Arrays.asList(arrayOfString));

        List list = this.onlCgformHeadService.list(lambdaQueryWrapper);
        if (list == null) {
            return Result.error("未找到对应实体");
        }
        return Result.ok(list);
    }


    @PostMapping({"/enhanceJs/{code}"})
    public Result<?> a(@PathVariable("code") String paramString, @RequestBody OnlCgformEnhanceJs paramOnlCgformEnhanceJs) {
        try {
            paramOnlCgformEnhanceJs.setCgformHeadId(paramString);
            this.onlCgformHeadService.saveEnhance(paramOnlCgformEnhanceJs);
            return Result.ok("保存成功!");
        } catch (Exception exception) {
            a.error(exception.getMessage(), exception);
            return Result.error("保存失败!");
        }
    }

    @GetMapping({"/enhanceJs/{code}"})
    public Result<?> a(@PathVariable("code") String paramString, HttpServletRequest paramHttpServletRequest) {
        try {
            String str = paramHttpServletRequest.getParameter("type");
            OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhance(paramString, str);
            if (onlCgformEnhanceJs == null) {
                return Result.error("查询为空");
            }
            return Result.ok(onlCgformEnhanceJs);
        } catch (Exception exception) {
            a.error(exception.getMessage(), exception);
            return Result.error("查询失败!");
        }
    }

    @PutMapping({"/enhanceJs/{code}"})
    public Result<?> b(@PathVariable("code") String paramString, @RequestBody OnlCgformEnhanceJs paramOnlCgformEnhanceJs) {
        try {
            paramOnlCgformEnhanceJs.setCgformHeadId(paramString);
            this.onlCgformHeadService.editEnhance(paramOnlCgformEnhanceJs);
            return Result.ok("保存成功!");
        } catch (Exception exception) {
            a.error(exception.getMessage(), exception);
            return Result.error("保存失败!");
        }
    }


    @GetMapping({"/enhanceButton/{formId}"})
    public Result<?> b(@PathVariable("formId") String paramString, HttpServletRequest paramHttpServletRequest) {
        try {
            List list = this.onlCgformHeadService.queryButtonList(paramString);
            if (list == null || list.size() == 0) {
                return Result.error("查询为空");
            }
            return Result.ok(list);
        } catch (Exception exception) {
            a.error(exception.getMessage(), exception);
            return Result.error("查询失败!");
        }
    }


    @PostMapping({"/enhanceSql/{formId}"})
    public Result<?> a(@PathVariable("formId") String paramString, @RequestBody OnlCgformEnhanceSql paramOnlCgformEnhanceSql) {
        try {
            paramOnlCgformEnhanceSql.setCgformHeadId(paramString);
            this.onlCgformHeadService.saveEnhance(paramOnlCgformEnhanceSql);
            return Result.ok("保存成功!");
        } catch (Exception exception) {
            a.error(exception.getMessage(), exception);
            return Result.error("保存失败!");
        }
    }

    @GetMapping({"/enhanceSql/{formId}"})
    public Result<?> c(@PathVariable("formId") String paramString, HttpServletRequest paramHttpServletRequest) {
        try {
            String str = paramHttpServletRequest.getParameter("buttonCode");
            OnlCgformEnhanceSql onlCgformEnhanceSql = this.onlCgformHeadService.queryEnhanceSql(paramString, str);
            if (onlCgformEnhanceSql == null) {
                return Result.error("查询为空");
            }
            return Result.ok(onlCgformEnhanceSql);
        } catch (Exception exception) {
            a.error(exception.getMessage(), exception);
            return Result.error("查询失败!");
        }
    }

    @PutMapping({"/enhanceSql/{formId}"})
    public Result<?> b(@PathVariable("formId") String paramString, @RequestBody OnlCgformEnhanceSql paramOnlCgformEnhanceSql) {
        try {
            paramOnlCgformEnhanceSql.setCgformHeadId(paramString);
            this.onlCgformHeadService.editEnhance(paramOnlCgformEnhanceSql);
            return Result.ok("保存成功!");
        } catch (Exception exception) {
            a.error(exception.getMessage(), exception);
            return Result.error("保存失败!");
        }
    }


    @PostMapping({"/enhanceJava/{formId}"})
    public Result<?> a(@PathVariable("formId") String paramString, @RequestBody OnlCgformEnhanceJava paramOnlCgformEnhanceJava) {
        try {
            if (!org.dfzt.modules.online.cgform.util.b.a(paramOnlCgformEnhanceJava)) {
                return Result.error("类实例化失败，请检查!");
            }
            paramOnlCgformEnhanceJava.setCgformHeadId(paramString);
            if (this.onlCgformHeadService.checkOnlyEnhance(paramOnlCgformEnhanceJava)) {
                this.onlCgformHeadService.saveEnhance(paramOnlCgformEnhanceJava);
                return Result.ok("保存成功!");
            }
            return Result.error("保存失败,数据不唯一!");
        } catch (Exception exception) {
            a.error(exception.getMessage(), exception);
            return Result.error("保存失败!");
        }
    }

    @GetMapping({"/enhanceJava/{formId}"})
    public Result<?> b(@PathVariable("formId") String paramString, OnlCgformEnhanceJava paramOnlCgformEnhanceJava) {
        try {
            paramOnlCgformEnhanceJava.setCgformHeadId(paramString);
            OnlCgformEnhanceJava onlCgformEnhanceJava = this.onlCgformHeadService.queryEnhanceJava(paramOnlCgformEnhanceJava);
            if (onlCgformEnhanceJava == null) {
                paramOnlCgformEnhanceJava.setCgJavaValue(null);
                return Result.ok(paramOnlCgformEnhanceJava);
            }
            return Result.ok(onlCgformEnhanceJava);
        } catch (Exception exception) {
            a.error(exception.getMessage(), exception);
            return Result.error("查询失败!");
        }
    }


    @GetMapping({"/enhanceJavaByButtonCode/{formId}"})
    public Result<?> c(@PathVariable("formId") String paramString, OnlCgformEnhanceJava paramOnlCgformEnhanceJava) {
        try {
            LambdaQueryWrapper<OnlCgformEnhanceJava> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OnlCgformEnhanceJava::getButtonCode, paramOnlCgformEnhanceJava.getButtonCode());
            lambdaQueryWrapper.eq(OnlCgformEnhanceJava::getCgformHeadId, paramString);
            OnlCgformEnhanceJava onlCgformEnhanceJava = (OnlCgformEnhanceJava) this.onlCgformEnhanceJavaMapper.selectOne(lambdaQueryWrapper);
            if (onlCgformEnhanceJava == null) {
                return Result.error("查询为空");
            }
            a.info("---------enhanceJavaByButtonCode-----------" + onlCgformEnhanceJava.toString());
            return Result.ok(onlCgformEnhanceJava);
        } catch (Exception exception) {
            a.error(exception.getMessage(), exception);
            return Result.error("查询失败!");
        }
    }

    @PutMapping({"/enhanceJava/{formId}"})
    public Result<?> d(@PathVariable("formId") String paramString, @RequestBody OnlCgformEnhanceJava paramOnlCgformEnhanceJava) {
        try {
            if (!org.dfzt.modules.online.cgform.util.b.a(paramOnlCgformEnhanceJava)) {
                return Result.error("类实例化失败，请检查!");
            }
            paramOnlCgformEnhanceJava.setCgformHeadId(paramString);
            if (this.onlCgformHeadService.checkOnlyEnhance(paramOnlCgformEnhanceJava)) {
                this.onlCgformHeadService.editEnhance(paramOnlCgformEnhanceJava);
                return Result.ok("保存成功!");
            }
            return Result.error("保存失败,数据不唯一!");
        } catch (Exception exception) {
            a.error(exception.getMessage(), exception);
            return Result.error("保存失败!");
        }
    }


    @GetMapping({"/queryTables"})
    public Result<?> a(HttpServletRequest paramHttpServletRequest) {
        String str = JwtUtil.getUserNameByToken(paramHttpServletRequest);
        if (!"admin".equals(str)) {
            return Result.error("noadminauth");
        }
        List<String> list1 = new ArrayList<>();
        try {
            list1 = DbReadTableUtil.a();
        } catch (SQLException sQLException) {
            a.error(sQLException.getMessage(), sQLException);
            return Result.error("同步失败，未获取数据库表信息");
        }
        org.dfzt.modules.online.cgform.util.b.b(list1);
        List list2 = this.onlCgformHeadService.queryOnlinetables();
        list1.removeAll(list2);
        ArrayList arrayList = new ArrayList();
        for (String str1 : list1) {
            if (h(str1)) {
                continue;
            }
            HashMap hashMap = new HashMap();
            hashMap.put("id", str1);
            arrayList.add(hashMap);
        }
        return Result.ok(arrayList);
    }


    @PostMapping({"/transTables/{tbnames}"})
    public Result<?> d(@PathVariable("tbnames") String paramString, HttpServletRequest paramHttpServletRequest) {
        String str = JwtUtil.getUserNameByToken(paramHttpServletRequest);
        if (!"admin".equals(str)) {
            return Result.error("noadminauth");
        }
        if (oConvertUtils.isEmpty(paramString)) {
            return Result.error("未识别的表名信息");
        }
        if (c != null && c.equals(paramString)) {
            return Result.error("不允许重复生成!");
        }
        c = paramString;


        String[] arrayOfString = paramString.split(",");
        for (byte b1 = 0; b1 < arrayOfString.length; b1++) {
            if (oConvertUtils.isNotEmpty(arrayOfString[b1])) {
                int i = this.onlCgformHeadService.count((Wrapper) (new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, arrayOfString[b1]));
                if (i <= 0) {


                    a.info("[IP] [online数据库导入表]   --表名：" + arrayOfString[b1]);
                    try {
                        this.onlCgformHeadService.saveDbTable2Online(arrayOfString[b1]);
                    } catch (DBException e) {
                        e.printStackTrace();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        c = null;
        return Result.ok("同步完成!");
    }


    @GetMapping({"/rootFile"})
    public Result<?> a() {
        JSONArray jSONArray = new JSONArray();
        File[] arrayOfFile = File.listRoots();
        for (File file : arrayOfFile) {
            JSONObject jSONObject = new JSONObject();
            if (file.isDirectory()) {
                System.out.println(file.getPath());
                jSONObject.put("key", file.getAbsolutePath());
                jSONObject.put("title", file.getPath());
                jSONObject.put("opened", Boolean.valueOf(false));
                JSONObject jSONObject1 = new JSONObject();
                jSONObject1.put("icon", "custom");
                jSONObject.put("scopedSlots", jSONObject1);
                jSONObject.put("isLeaf", Boolean.valueOf((file.listFiles() == null || file.listFiles().length == 0)));
            }
            jSONArray.add(jSONObject);
        }
        return Result.ok(jSONArray);
    }


    @GetMapping({"/fileTree"})
    public Result<?> e(@RequestParam(name = "parentPath", required = true) String paramString) {
        JSONArray jSONArray = new JSONArray();
        File file = new File(paramString);
        File[] arrayOfFile = file.listFiles();
        for (File file1 : arrayOfFile) {
            if (file1.isDirectory() && oConvertUtils.isNotEmpty(file1.getPath())) {
                JSONObject jSONObject1 = new JSONObject();
                System.out.println(file1.getPath());
                jSONObject1.put("key", file1.getAbsolutePath());
                jSONObject1.put("title", file1.getPath().substring(file1.getPath().lastIndexOf(File.separator) + 1));
                jSONObject1.put("isLeaf", Boolean.valueOf((file1.listFiles() == null || file1.listFiles().length == 0)));
                jSONObject1.put("opened", Boolean.valueOf(false));
                JSONObject jSONObject2 = new JSONObject();
                jSONObject2.put("icon", "custom");
                jSONObject1.put("scopedSlots", jSONObject2);
                jSONArray.add(jSONObject1);
            }
        }

        return Result.ok(jSONArray);
    }


    @GetMapping({"/tableInfo"})
    public Result<?> f(@RequestParam(name = "code", required = true) String paramString) {
        OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(paramString);
        if (onlCgformHead == null) {
            return Result.error("未找到对应实体");
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("main", onlCgformHead);
        if (onlCgformHead.getTableType() == 2) {

            String str = onlCgformHead.getSubTableStr();
            if (oConvertUtils.isNotEmpty(str)) {
                ArrayList<OnlCgformHead> arrayList = new ArrayList<>();
                String[] arrayOfString = str.split(",");
                for (String str1 : arrayOfString) {
                    LambdaQueryWrapper<OnlCgformHead> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(OnlCgformHead::getTableName, str1);
                    OnlCgformHead onlCgformHead1 = (OnlCgformHead) this.onlCgformHeadService.getOne(lambdaQueryWrapper);
                    arrayList.add(onlCgformHead1);
                }

                Collections.sort(arrayList, (Comparator<OnlCgformHead>) (param1OnlCgformHead1, param1OnlCgformHead2) -> {
                    Integer integer1 = param1OnlCgformHead1.getTabOrderNum();
                    if (integer1 == null) {
                        integer1 = Integer.valueOf(0);
                    }
                    Integer integer2 = param1OnlCgformHead2.getTabOrderNum();
                    if (integer2 == null) {
                        integer2 = Integer.valueOf(0);
                    }
                    return integer1.compareTo(integer2);
                });
                hashMap.put("sub", arrayList);
            }
        }


        Integer integer = onlCgformHead.getTableType();
        if ("Y".equals(onlCgformHead.getIsTree())) {
            integer = Integer.valueOf(3);
        }
        List list = CgformEnum.getJspModelList(integer.intValue());

        hashMap.put("jspModeList", list);
//    String var0 = new ResourceBundle().getString("project_path");
        hashMap.put("projectPath", org.jeecgframework.codegenerate.a.a.m());
        return Result.ok(hashMap);
    }


    @PostMapping({"/copyOnline"})
    public Result<?> g(@RequestParam(name = "code", required = true) String paramString) {
        try {
            OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(paramString);
            if (onlCgformHead == null) {
                return Result.error("未找到对应实体");
            }
            this.onlCgformHeadService.copyOnlineTableConfig(onlCgformHead);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return Result.ok();
    }


    private boolean h(String paramString) {
        for (String str : b) {
            if (paramString.startsWith(str) || paramString.startsWith(str.toUpperCase())) {
                return true;
            }
        }
        return false;
    }
}
